

package com.feiyuan.admin.app.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feiyuan.admin.app.utils.JwtUtils;
import com.feiyuan.common.exception.RRException;
import com.feiyuan.common.helper.SMSHelper;
import com.feiyuan.common.utils.CommonUtils;
import com.feiyuan.common.utils.Constant;
import com.feiyuan.common.validator.Assert;
import com.feiyuan.admin.app.dao.UserDao;
import com.feiyuan.admin.app.entity.UserEntity;
import com.feiyuan.admin.app.form.LoginForm;
import com.feiyuan.admin.app.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	private final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private SMSHelper smsHelper;

	@Autowired
	private JwtUtils jwtUtils;

	@Override
	public UserEntity queryByMobile(String mobile) {
		return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile));
	}

	@Override
	public long login(LoginForm form) {
		UserEntity user = queryByMobile(form.getMobile());
		if (user == null) {
			user = new UserEntity();
			user.setMobile(form.getMobile());
			user.setCreateTime(new Date());
			this.baseMapper.insert(user);
		} else {
			Assert.isNull(user, "手机号错误");
		}

		//密码错误
//		if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
//			throw new RRException("手机号或密码错误");
//		}
		// 验证码是否正确
		if (redisTemplate.hasKey(Constant.SEND_APP_CODE + form.getMobile())) {
			String code = (String) redisTemplate.opsForValue().get(Constant.SEND_APP_CODE + form.getMobile());
			if (!form.getCode().equals(code)) {
				throw new RRException("验证码输入错误!", 500);
			}
		} else {
			throw new RRException("验证码过期!", 500);
		}

		// 删除验证码
		redisTemplate.delete(Constant.SEND_APP_CODE + form.getMobile());

		// 放入缓存
		redisTemplate.opsForValue().set(Constant.APP_USER_KEY + form.getMobile(), JSONObject.toJSONString(user), 30 * 24 * 60 * 60, TimeUnit.SECONDS);

		return user.getUserId();
	}

	@Override
	public Boolean sendCode(String mobile) {
		//生成token
		String token = jwtUtils.generateToken(1);
		String code = CommonUtils.generateCode();

		// TODO 调用阿里短信接口
		// 发送验证码到手机
		String templateParams = "{'code':" + "'" + code + "'}";
		log.info("templateParams:{}", templateParams);
//        Map<String, String> smsMap = smsHelper.sendMessage(mobile, "SMS_190782144", templateParams);
//        if (!smsMap.get("code").equals("OK")) {
//            throw new RRException(String.valueOf(smsMap.get("msg")), 500);
//        }

		redisTemplate.opsForValue().set(Constant.SEND_APP_CODE + mobile, code, 5 * 60, TimeUnit.SECONDS);

		return true;
	}

	@Override
	public Boolean logout(String mobile, HttpServletRequest request) {
		String token = request.getHeader(jwtUtils.getHeader());
		if (redisTemplate.delete(Constant.APP_USER_KEY + token)) {
			return true;
		}
		return false;
	}

	@Override
	public com.feiyuan.common.entity.UserEntity queryById(Long userId) {
		UserEntity user = this.getById(userId);
		com.feiyuan.common.entity.UserEntity userEntity = new com.feiyuan.common.entity.UserEntity();
		BeanUtils.copyProperties(user, userEntity);
		return userEntity;
	}

	@Override
	public Map<String, Object> newLogin(LoginForm form) {
		Map<String, Object> map = new HashMap<>();

		UserEntity user = queryByMobile(form.getMobile());
		if (user == null) {
			user = new UserEntity();
			user.setMobile(form.getMobile());
			user.setCreateTime(new Date());
			this.baseMapper.insert(user);
		} else {
			Assert.isNull(user, "手机号错误");
		}

		//密码错误
//		if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
//			throw new RRException("手机号或密码错误");
//		}
		// 验证码是否正确
		if (redisTemplate.hasKey(Constant.SEND_APP_CODE + form.getMobile())) {
			String code = (String) redisTemplate.opsForValue().get(Constant.SEND_APP_CODE + form.getMobile());
			if (!form.getCode().equals(code)) {
				throw new RRException("验证码输入错误!", 500);
			}
		} else {
			throw new RRException("验证码过期!", 500);
		}

		// 删除验证码
		redisTemplate.delete(Constant.SEND_APP_CODE + form.getMobile());

		//生成token
        String token = jwtUtils.generateToken(user.getUserId());

		// 放入缓存
		redisTemplate.opsForValue().set(Constant.APP_USER_KEY + token, JSONObject.toJSONString(user), 30 * 24 * 60 * 60, TimeUnit.SECONDS);

		map.put("token", token);
        map.put("expire", jwtUtils.getExpire());

		return map;
	}
}
